<template>
    <div class="main">
        <div class="goods-introduce">
            <el-card class="box-card">
                <h4>商品(sku)介绍</h4>
                <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px"
                    class="demo-ruleForm">
                    <el-form-item label="商品名称" prop="title" class="is-required">
                        <el-input v-model="ruleForm.title" autocomplete="off" placeholder="请输入商品名称" />
                    </el-form-item>
                    <el-form-item label="原价" prop="originalPrice" class="is-required">
                        <el-input v-model.number="ruleForm.originalPrice">
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="现价" prop="price" class="is-required">
                        <el-input v-model.number="ruleForm.price">
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="VIP价格" prop="vipPrice" class="is-required">
                        <el-input v-model.number="ruleForm.vipPrice">
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="剩余库存">
                        <el-input :disabled="true" :value='0' />
                    </el-form-item>
                    <el-form-item label="运费模板">
                        <el-select v-model="ruleForm.freightTemplateId" placeholder="选择商品运费模板" clearable>
                            <el-option v-for="item in freightTemplate" :label="item.title" :value="item.id"
                                :key="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否在售" prop="status" class="is-required">
                        <el-radio-group v-model="ruleForm.status" class="ml-4">
                            <el-radio :label="1" size="large">在售</el-radio>
                            <el-radio :label="0" size="large">下架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品图片">
                        <el-upload :file-list="ruleForm.imgList" :headers="headers" :action="action.url"
                            list-type="picture-card" :on-remove="handleRemove" :limit="5" :on-exceed="handlerExceed"
                            :on-success="handleAvatarSuccess">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品单位" prop="unit" class="is-required">
                        <el-input v-model="ruleForm.unit" placeholder="件/个/盒" />
                    </el-form-item>
                    <el-form-item label="所属类目">
                        <el-cascader v-model="ruleForm.categoryId" :options="options" :props="props" clearable
                            placeholder="请选择" />
                    </el-form-item>
                    <el-form-item label="商品简介">
                        <el-input v-model="ruleForm.description" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="商品详细介绍" class="is-required">
                        <div style="width:100%">
                            <TEditor ref="editor" v-model="ruleForm.detail" @getContent="getContent"
                                style="border-radius: 10px;"></TEditor>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
        <div class="goods-parameters">
            <el-card>
                <h4>商品参数</h4>
                <el-button type="primary" plain @click="addParamList">添加</el-button>
                <el-table :data="ruleForm.attributeList" style="width: 100%">
                    <el-table-column prop="attribute" label="商品参数名称" />
                    <el-table-column prop="value" label="商品参数值" />
                    <el-table-column label="操作" align='center'>
                        <template #default="scope">
                            <el-button type="danger"
                                @click="ruleForm.attributeList.splice(scope.$index, 1)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>
        <div class="goods-specifications">
            <el-card>
                <h4>规格维度</h4>
                <el-button type="primary" plain @click="addDimensionList" :disabled="true">添加</el-button>
                <el-table :data="ruleForm.specificationList" style="width: 100%">
                    <el-table-column prop="gmtUpdate" label="维度ID" />
                    <el-table-column prop="title" label="维度名称" />
                    <el-table-column label="创建时间">
                        <template #default="scope">
                            <template v-if="scope.row.gmtCreate != 0">
                                {{ new Date(scope.row.gmtCreate).friendTime(1) }}
                            </template>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="操作" align='center'>
                        <template #default="scope">
                            <el-button type="primary"
                                @click="handlerEditDimension(scope.row, scope.$index)">编辑</el-button>
                            <el-button type="danger" @click="handlerDeleteDimesion(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column> -->
                </el-table>
            </el-card>
        </div>
        <div class="goods-sku">
            <el-card>
                <h4>商品(Sku)详情</h4>
                <div class="goods-sku-batchpricing"> <el-button type="primary" plain @click="handlerBitchPrice"
                        :disabled="ruleForm.skuList.length == 0">批量定价</el-button></div>
                <!-- tag标签 -->
                <div class="tag-container" v-for="item in ruleForm.specificationList">
                    <el-tag style="margin:10px 10px 10px 20px;" type="warning">{{ item.title }}</el-tag>
                    <el-tag v-for="tag in item.values" :key="tag" class="mx-1" closable :disable-transitions="false"
                        @close="handleClose(item, tag)">
                        {{ tag }}
                    </el-tag>
                    <el-input v-if="item.inputSkuTagVisible" ref="InputRef" v-model.trim="item.inputSkuTagValue"
                        class="ml-1 w-20" size="small" @keyup.enter.native="handleInputConfirm(item)"
                        @blur="handleInputConfirm(item)" style="width: 80px;" />
                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(item)">
                        + 添加
                    </el-button>
                </div>
                <div class="goods-sku-table">
                    <el-table :data="ruleForm.skuList" :span-method="handlerSpanMethod" style="width: 100%;" border>
                        <el-table-column
                            v-for="(item, index) in ruleForm.specificationList.filter(item => item.values.length > 0)"
                            :prop="'id_' + item.title" :label="item.title" />
                        <el-table-column prop="skuId" label="SkuId" width="120" align='center' />
                        <el-table-column label="￥价格(元)" width="200" align='center'>
                            <template #default="scope">
                                <el-input-number v-model="scope.row.price" :min="0" />
                            </template>
                        </el-table-column>
                        <el-table-column label="￥VIP价(元)" width="200" align='center'>
                            <template #default="scope">
                                <el-input-number v-model="scope.row.vipPrice" :min="0" />
                            </template>
                        </el-table-column>
                        <el-table-column label="￥吊牌价(元)" width="200" align='center'>
                            <template #default="scope">
                                <el-input-number v-model="scope.row.originalPrice" :min="0" />
                            </template>
                        </el-table-column>
                        <el-table-column label="库存(件)" width="200" align='center'>
                            <template #default="scope">
                                <el-input-number v-model="scope.row.stock" :min="0" />
                            </template>
                        </el-table-column>
                        <el-table-column label="重量(克)" width="200" align='center'>
                            <template #default="scope">
                                <el-input-number v-model="scope.row.weight" :min="0" />
                            </template>
                        </el-table-column>
                        <el-table-column label="SKU图片" width="200" align='center'>
                            <template v-slot="scope">
                                <el-upload :show-file-list="false" :action="action.url"
                                    :before-upload="beforeAvatarUpload" :headers="headers"
                                    :on-success="handleAvatarSuccesse" :on-remove="handleRemove">
                                    <img v-if="scope.row.img" width="50" height="50" :src="scope.row.img"
                                        class="avatar">
                                    <div v-else @click.capture="changeCurrentRow(scope.$index)">
                                        <el-button type="primary" :icon="Upload"></el-button>
                                    </div>
                                </el-upload>
                            </template>
                        </el-table-column>
                        <el-table-column label="条形码" width="200" align='center'>
                            <template #default="scope">
                                <el-input v-model="scope.row.barCode">
                                    <template #append>
                                        <el-button @click="scope.row.barCode = new Date().getTime()">随机</el-button>
                                    </template>
                                </el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div>
                    <el-dialog v-model="centerDialogVisible" :title="title" width="40%" align-center destroy-on-close>
                        <el-form ref="rule" :model="dialogForm" status-icon :rules="rulest" label-width="120px"
                            class="demo-ruleForm">
                            <el-form-item label="设置商品名称" prop="attribute" class="is-required" v-if="num == 1">
                                <el-input v-model.trim="dialogForm.attribute" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="商品参数值" prop="value" class="is-required" v-if="num == 1">
                                <el-input v-model.trim="dialogForm.value" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="类型名称" prop="title" class="is-required" v-if="num == 2">
                                <el-input v-model.trim="dialogForm.title" />
                            </el-form-item>
                            <el-form-item label="现价(￥)" v-if="num == 3" label-width="13vw">
                                <el-input-number v-model.number="dialogForm.price" :min="0" />
                            </el-form-item>
                            <el-form-item label="VIP价格(￥)" v-if="num == 3" label-width="13vw">
                                <el-input-number v-model.number="dialogForm.vipPrice" :min="0" />
                            </el-form-item>
                            <el-form-item label="吊牌价(￥)" v-if="num == 3" label-width="13vw">
                                <el-input-number v-model.number="dialogForm.originalPrice" :min="0" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer" v-if="num != 3">
                                <el-button @click="centerDialogVisible = false">取消</el-button>
                                <el-button type="primary" @click="confirm(rule)">
                                    确定
                                </el-button>
                            </span>
                            <span class="dialog-footer" v-else>
                                <el-button @click="centerDialogVisible = false">取消</el-button>
                                <el-button type="primary" @click="resure">
                                    确定
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                </div>
            </el-card>
        </div>
        <!-- 底部提交按钮 -->
        <div class="bottom-wrap">
            <el-button type="primary" @click="handleCancel">关闭</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">更改商品</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref, nextTick } from 'vue'
import type { FormInstance, UploadProps, TableColumnCtx } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'
import { ClassGoodsAddList, ClassSpecificationList, ClassSkuList } from "#/index";
import { post } from "@/utils/http";
import cookie from "js-cookie";
import { useRouter,useRoute } from "vue-router";
import { ElInput } from 'element-plus'
import '@/utils/dataFriend'
import { ElMessage, ElMessageBox } from 'element-plus'
import TEditor from "@/components/tinymce/TEditor.vue";
import { useTagsStore } from "@/stores/tags";


interface User {
    id: string
    name: string
    amount1: string
    amount2: string
    amount3: number
}

interface SpanMethodProps {
    row: object,
    column: object,
    rowIndex: number,
    columnIndex: number
}
let prop = defineProps(['id'])
let indexRow = 0
let title = ref('')
const store = useTagsStore()
let num = ref(1) //用来判断是规格还是维度等哪个弹出框
let router = useRouter() //获取全部路由
let route = useRoute()
const centerDialogVisible = ref(false) //规格、商品参数、批量定价弹窗显示隐藏
const ruleFormRef = ref<FormInstance>()
const rule = ref() //获取规格和维度等节点对象的引用
const InputRef = ref()  //获取tag里面的iupt对象节点的引用
const ruleForm = reactive(new ClassGoodsAddList) //表单数据
const freightTemplate: TypeFreightTemplateId[] = reactive([]) //运费模板
const options: TypeCategory[] = reactive([]) //类目列表
let dialogForm = reactive({
    attribute: '', //商品名称
    value: '', //商品参数
    title: '', //类型名称
    price: 1, //现价
    vipPrice: 1, //VIP价格
    originalPrice: 1  //吊牌价
})
let skuLength = ref(0) //总共生成多少个数据，有多少行
const newdialogForm = reactive({ ...dialogForm })
const props = {
    emitPath: false,
    value: 'id',
    label: 'title',
    children: 'childrenList'
}
const headers = reactive({  //上传图片获取请求头
    AdminToken: cookie.get('token')
})

const getContent = (v: string) => {
    ruleForm.detail = v
}
//判断是开发环境还是上线
const action = reactive({
    url: process.env.NODE_ENV === 'development' ? '/upload/admin' : 'http://zxwyit.cn:8989/upload/admin'
})
//商品名称非空验证
const validateNonempty = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入内容'))
    }
    callback()
}
//原价验证
const validateOriginalPrice = (rule: any, value: any, callback: any) => {
    var regexp = /^\d{1,}$/
    if (value === '' && !regexp.test(value)) {
        callback(new Error('请输入内容'))
    } else if (!regexp.test(value)) {
        callback(new Error('内容必须是数字'))
    } else if (value < ruleForm.price) {
        callback(new Error('原价不能小于现价'))
    } else if (value < ruleForm.vipPrice) {
        callback(new Error('原价不能小于VIP价格'))
    }
    callback()
}
//现价验证
const validatePrice = (rule: any, value: any, callback: any) => {
    var regexp = /^\d{1,}$/
    if (value === '') {
        callback(new Error('请输入内容'))
    } else if (!regexp.test(value)) {
        callback(new Error('内容必须是数字'))
    } else if (value > ruleForm.originalPrice) {
        callback(new Error('现价必须小于原价'))
    } else if (value < ruleForm.vipPrice) {
        callback(new Error('现价不能大于VIP价格'))
    }
    callback()
}
//VIP验证
const validateVipPrice = (rule: any, value: any, callback: any) => {
    var regexp = /^\d{1,}$/
    if (value === '') {
        callback(new Error('请输入内容'))
    } else if (!regexp.test(value)) {
        callback(new Error('内容必须是数字'))
    } else if (value > ruleForm.price) {
        callback(new Error('VIP价格必须小于现价'))
    } else if (value > ruleForm.originalPrice) {
        callback(new Error('VIP价格必须小于原价'))
    }
    callback()
}


const rules = reactive({
    title: [{ validator: validateNonempty, trigger: 'blur' }],
    originalPrice: [{ validator: validateOriginalPrice, trigger: 'blur' }],
    price: [{ validator: validatePrice, trigger: 'blur' }],
    vipPrice: [{ validator: validateVipPrice, trigger: 'blur' }],
    unit: [{ validator: validateNonempty, trigger: 'blur' }],

})
const rulest = reactive({
    attribute: [{ validator: validateNonempty, trigger: 'blur' }],
    value: [{ validator: validateNonempty, trigger: 'blur' }],
})

//商品参数添加
const addParamList = () => {
    centerDialogVisible.value = true
    title.value = '设置商品参数'
    num.value = 1
    Object.assign(dialogForm, newdialogForm)
}

//规格维度添加
const addDimensionList = () => {
    centerDialogVisible.value = true
    title.value = '创建规格'
    num.value = 2
    Object.assign(dialogForm, newdialogForm)
}

//批量定价添加
const handlerBitchPrice = () => {
    centerDialogVisible.value = true
    title.value = '批量定价'
    num.value = 3
    Object.assign(dialogForm, newdialogForm)
}

/**
 * 类目列表
 * */
const lodeCategory = () => {
    let data = {
        _gp: 'admin.category',
        _mt: 'categoryTree'
    }
    if (options.length == 0) {
        post(data).then(res => {
            console.log(res);
            if (200 == res.errno) {
                options.length = 0
                options.push(...res.data)
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }
}
lodeCategory()
/**
 * 显示运费列表
 */
const loadFreightTemplate = () => {
    let freightData = {
        _gp: 'admin.freight',
        _mt: 'list',
    }
    post(freightData).then(res => {
        freightTemplate.length = 0;
        freightTemplate.push(...res.data)
        console.log(res)
    })
}
loadFreightTemplate()
/**
 * 生成skus
 */
const skuDataList = () => {
    //过滤掉商品维度数据里面的values数组
    const skuTagsList = ruleForm.specificationList.filter(item => item.values.length).map(items => items.values)
    const name = ruleForm.specificationList.filter(item => item.values.length).map(v => v.title)
    if (skuTagsList.length == 0) return ruleForm.skuList = []
    //使用笛卡尔积算法将数据进行交叉处理
    let arr = skuTagsList.reduce(
        (total: string[][], current) => {
            let temp: string[][] = []
            total.forEach(item => {
                current.forEach(v => {
                    temp.push(item.concat([v]))
                })
            })
            return temp
        }, [[]])
    console.log(name);
    // 进行拼接数据
    let list = arr.map(item => {
        let obj: any = new ClassSkuList()
        item.forEach((val, index) => {
            obj['id_' + name[index]] = val  // 相当于是添加一个对象
            obj['title'] = item.join(',')
            obj.specification += ruleForm.specificationList[index].title + '_' + val + ','
        })
        // obj.title = obj.title.slice(0, obj.title.length - 1)
        return obj
    })
    skuLength.value = list.length
    ruleForm.skuList.length = 0
    ruleForm.skuList.push(...list)
    // console.log(ruleForm.skuList, 6666);
    // console.log(ruleForm.specificationList, 5555);
}


/**
 * 删除成功之后的函数
 */
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    let imgList:any = []
    uploadFiles.forEach(item =>{
        imgList.push(item.url)
    })
    // console.log(imgList);
    ruleForm.imgList = imgList
}
/**
 * 图片超出数量之后的函数
 * @param files 上传的文件
 */
const handlerExceed: UploadProps['onExceed'] = (files) => {
    ElMessage.warning('图片数量不能超过5张')
}

/**
 * 广告上传图片成功之后的函数
 * @param response 响应成功的回调
 * @param uploadFile 上传的文件
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    if (200 == response.errno) {
        let url = response.url
        ruleForm.imgList.push({url: response.url})
    }
}
//获取当前skuList数组的下标
const changeCurrentRow = (index: number) => {
    indexRow = index
}
/**
 * SKU上传图片之前的函数判断
 * @param response 响应成功的回调
 * @param uploadFile 上传的文件
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    let imgar = rawFile.type === 'image/jpeg' || rawFile.type === 'image/jpg' || rawFile.type === 'image/png'
    if (!imgar) {
        ElMessage.error('格式错误!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('图片大小不能超过1MB!')
        return false
    }
    return true
}

/**
 * SKU上传图片成功之后的函数
 * @param response 响应成功的回调
 * @param uploadFile 上传的文件
 */
const handleAvatarSuccesse: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    if (200 == response.errno) {
        ruleForm.skuList[indexRow].img = response.url // 得到上传图片成功的路径
    }
}

/**
 * 商品规格维度编辑
*/
const handlerEditDimension = (row: ClassSpecificationList, index: number) => {
    centerDialogVisible.value = true
    num.value = 2
    title.value = '修改规格维度'
    dialogForm.title = row.title
    indexRow = index
}
/**
 * 商品规格维度删除
 * @param index 当前下标
*/
const handlerDeleteDimesion = (index: number) => {
    ruleForm.specificationList.splice(index, 1)
    skuDataList()
}
/**
 * 输入框失焦事件
 */
const handleInputConfirm = (item: ClassSpecificationList) => {
    let inputValue = item.inputSkuTagValue;
    if (inputValue) {
        //往当前的values数组添加inputValue
        let index = item.values.findIndex(v => v == inputValue)
        if (index == -1) {
            item.values.push(inputValue)
        } else {
            ElMessage.warning('名称已存在')
        }
    }
    skuDataList()
    item.inputSkuTagVisible = false
    item.inputSkuTagValue = ''
}
/**
 * 删除tag标签页
 * @param item specificationList数组中的每个元素
 * @param tag  当前行数据
*/
const handleClose = (item: ClassSpecificationList, tag: string) => {
    item.values.splice(item.values.indexOf(tag), 1)
    skuDataList()
}
/**
 * 显示输入框
* @param item specificationList数组中的每个元素
*/
const showInput = (item: ClassSpecificationList) => {
    item.inputSkuTagVisible = true
    nextTick(() => {
        InputRef.value[0].focus()
    })
}
/**
 * 表格跨行跨列
 */
const handlerSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
    let specList = ruleForm.specificationList.filter(item => item.values.length > 0) //过滤掉规格维度数组中values有没有值
    if (columnIndex < specList.length - 1) { //对要跨行的列进行计算，排除最后一个属性列(最后一个属性不存在)
        let rowSpanNum = 1  //跨行的数量
        for (let index = columnIndex + 1; index < specList.length; index++) {
            rowSpanNum *= specList[index].values.length //跨行的数量-后面属性值数量的成绩
        }
        if (rowIndex % rowSpanNum === 0) { //每次跨行的数量相同,所以当前行索引号%跨行数量==0就是要跨行的开始
            return { rowspan: rowSpanNum, colspan: 1 }
        } else {
            return { rowspan: 0, colspan: 0 }
        }
    }
}
//商品参数确认和规格维度确认
const confirm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (1 == num.value && title.value == '设置商品参数') {
                ruleForm.attributeList.push({ attribute: dialogForm.attribute, value: dialogForm.value })
                console.log(ruleForm.attributeList);
            } else if (2 == num.value && title.value == '创建规格') {
                let specifications = new ClassSpecificationList
                specifications.title = dialogForm.title
                specifications.gmtCreate = new Date().getTime()
                specifications.gmtUpdate = +new Date()
                let index = ruleForm.specificationList.findIndex(item => item.title == dialogForm.title)
                if (index == -1) {
                    ruleForm.specificationList.push({ ...specifications })
                } else {
                    ElMessage.warning('规格名称已存在')
                }
            } else if (2 == num.value && title.value == '修改规格维度') {
                ruleForm.specificationList[indexRow].title = dialogForm.title
                skuDataList()
            }
            centerDialogVisible.value = false
        } else {
            console.log('error submit!')
            return false
        }
    })
}
//批量定价确认验证
const resure = () => {
    if (dialogForm.vipPrice < dialogForm.originalPrice && dialogForm.vipPrice < dialogForm.price && dialogForm.price < dialogForm.originalPrice) {
        ruleForm.skuList.map(item => {
            item.price = dialogForm.price
            item.vipPrice = dialogForm.price
            item.originalPrice = dialogForm.originalPrice
        })
        centerDialogVisible.value = false
    } else {
        return ElMessage.warning('批量定价vip价格必须小于现价并且vip价格小于原价并且现价小于原价!')
    }

}
//加载商品列表
const loadgoodseditList = () => {
    let id = prop.id
    let data = {
        _gp: 'admin.product',
        _mt: 'detail',
        spuId: id
    }
    post(data).then(res => {
        console.log(res, 222);
        let { errno, errmsg, data } = res
        if (200 == errno) {
            let imgage = res.data.imgList.map((item:string)=>{
              //判断是否是对象，如果以{开头代表对象
            return  item.startsWith('{')?JSON.parse(item).url.startsWith('{')?{url:JSON.parse(JSON.parse(item).url).url}:{url:JSON.parse(item).url}:{url:item}   
           })
            data.imgList.length = 0
            data.imgList.push(...imgage)
            //构造符合商品规格的数据结构
           // data.specificationList = data.skuList[0].specification.split(',').map((item: string) => item.split("_")[0]).map((item: string) => data.specificationList.find((items: ClassSpecificationList) => items.title === item))
            console.log(data.specificationList);
            
            //如果data.specificationList中有undefined就给它截取掉
            // data.specificationList.forEach((item:any,index:number)=>{
            //      if(item==undefined){
            //         data.specificationList.splice(data.specificationList.length-1)
            //      }
            // })
            //动态添加values字段
            // data.specificationList.forEach((item: ClassSpecificationList) => {
            //         item.values =[]
            // })
            data.specificationList = data.specificationList.map((item:ClassSpecificationList)=>({
                ...item,
                values:[]
            }))
            data.skuList.forEach((sku: any) => {
                let spec = sku.specification || ""
                spec.split(",").map((item: any) => item.split('_')).forEach((item: any) => {
                    let title = item[0]; //取出title
                    let val = item[1]; //取出val
                    sku['id_' + title] = val
                    var findSpec = data.specificationList.find((items: any) => items.title == title)
                    var indexs = findSpec?.values.indexOf(val)
                    if (-1 == indexs) {
                        findSpec.values.push(val)  //去重处理
                    }
                })
            });
            Object.assign(ruleForm,data)
        } else {
            ElMessage.error(errmsg)
        }
    })
}

loadgoodseditList()

/**
 * 关闭当前页面
 */
 const handleCancel = ()=>{
  store.removeTagBaPath(route.fullPath)
  router.push({name:'GoodsList'})
}

/**
 * 保存商品
*/
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (ruleForm.detail == '') {
                return ElMessage.warning('商品详细介绍不能为空')
            }
            let data = {
                _gp: 'admin.product',
                _mt: 'edit',
                spuDTO: JSON.stringify(ruleForm)
            }
            post(data).then(res => {
                let { errno, errmsg } = res
                if (200 == errno) {
                    ElMessageBox.confirm(
                        '修改成功,是否留在当前页面？',
                        '提示',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '返回商品列表',
                            type: 'warning',
                        }
                    )
                        .catch(() => {
                            handleCancel()
                        })
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}
</script>
<style lang="less" scoped>
.main {
    padding-bottom: 20px;

    .goods-introduce {
        .el-form {
            margin-left: 30px;
            margin-top: 10px;
        }

        .avatar-uploader .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        &::v-deep .avatar-uploader .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .avatar-uploader .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }

    .goods-parameters {
        h4 {
            margin-bottom: 10px;
        }
    }

    .goods-specifications {
        h4 {
            margin-bottom: 10px;
        }
    }

    .goods-sku {
        /deep/ .el-card__body {
            padding: 0px;
        }

        h4 {
            margin-top: 20px;
            margin-left: 20px;
            margin-bottom: 10px;
        }

        .goods-sku-batchpricing {
            padding-left: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid #ccc;
        }

        .tag-container {
            margin-top: 10px;

            .el-tag {
                margin-right: 10px;
            }
        }

        .goods-sku-table {
            padding: 20px;
        }
    }

    .bottom-wrap {
        text-align: right;
        padding: 20px;
    }
}
</style>
<!-- <template>
    <div>商品编辑:{{ prop.id }}</div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, watch } from 'vue'

</script> -->